﻿#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

class Solution
{
public:
    // 207. 课程表
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
    {
        unordered_map<int, vector<int>> edges;
        vector<int> in(numCourses);

        // 建图
        for (auto& p : prerequisites)
        {
            int a = p[0], b = p[1];
            edges[b].push_back(a);
            in[a]++;
        }

        // 拓扑排序
        queue<int> q;
        // 把入度为0的点加入队列
        for (int i = 0; i < numCourses; ++i)
        {
            if (in[i] == 0)
                q.push(i);
        }

        // bfs
        while (q.size())
        {
            int t = q.front();
            q.pop();

            for (auto e : edges[t])
            {
                in[e]--;
                if (in[e] == 0)
                    q.push(e);
            }
        }

        // 判断是否有环
        for (int i = 0; i < numCourses; ++i)
            if (in[i])
                return false;
        return true;
    }
};

int main()
{
    vector<vector<int>> v{ {1,0},{2,0},{3,0},{2,1},{3,1},{3,2},{4,3} };
    cout << Solution().canFinish(5, v) << endl;

    return 0;
}
